<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElDropdown, ElDropdownMenu, ElDropdownItem } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
// 引入组件
import AddProduct from './component/add.vue';
import EditProduct from './component/edit.vue';
import { deleteProductApi, getProductListApi } from "@/api/products/product";
import { getProductKeys } from "@/utils/appCommon/appCommonOptions/products";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";

//一定要和服务端的权限名称一样
defineOptions({
  name: "product-manage"
});


const i18n = useI18n();
const pageSizeOps = ref(pageSizeOptions)
const productKeys = ref([])
onMounted(async () => {
  console.log("product mounted");
  productKeys.value = await getProductKeys()
})
// 搜索处理 - 增加搜索参数存储
const searchParams = ref({
  name:undefined,
  productKey: undefined,
  type: undefined,
  openStatus: undefined,
  timeRange: [],
  page:1,
  pageSize: 10,
});
// 搜索字段配置 - 根据表结构更新
const searchFields = ref([
  {
    prop: "name",
    name: i18n.t("products.productPage.productName"),
    type: "input",
    placeholder: i18n.t("products.productPage.enterProductName"),
  },
  {
    prop: "productKey",
    name: i18n.t("products.productPage.productKey"),
    type: "select",
    formOptions : productKeys,
  },
  {
    prop: "type",
    name: i18n.t("products.productPage.deviceType"),
    type: "select",
    formOptions: [
      { val: 0, label: i18n.t("products.productPage.directDevice") },
      { val: 1, label: i18n.t("products.productPage.gatewayDevice") },
      { val: 2, label: i18n.t("products.productPage.subDevice") },
    ],
  },
  {
    prop: "openStatus",
    name: i18n.t("products.productPage.activationStatus"),
    type: "select",
    formOptions: [
      { val: 0, label: i18n.t("products.productPage.inactive") },
      { val: 1, label: i18n.t("products.productPage.active") },
    ],
  },
]);

// 产品列表数据
const productList = ref<any[]>([]);
const total = ref(0);

// 加载产品列表
const loadProductList = async () => {
  try {
    // 替换模拟数据为API调用
    const response = await getProductListApi({
      ...searchParams.value
    });
    if (response.code === 0) {
      if(!response.data.list){
        response.data.list = []
      }
      productList.value = response.data.list;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || i18n.t("products.productPage.getListFailed"));
    }
  } catch (error: any) {
    total.value = 0;
    ElMessage.error(i18n.t("products.productPage.getListFailed") + error.message);
    console.error('Failed to load product list:', error);
  }
};


const  handleChange = (e: any) => {
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
}
const handleSearch = async (e:any) => {
  searchParams.value.page = 1
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  await  loadProductList();
}
const handleReset = (e:any) => {
}

// 删除产品
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      i18n.t("products.productPage.deleteConfirm"),
      i18n.t("buttons.delete"),
      {
        confirmButtonText: i18n.t("buttons.confirm"),
        cancelButtonText: i18n.t("buttons.cancel"),
        type: 'warning',
      }
    );

    const response = await deleteProductApi(id);
    if (response.code === 0) {
      ElMessage.success(i18n.t("products.productPage.deleteSuccess"));
      await loadProductList();
    } else {
      ElMessage.error(response.msg || i18n.t("products.productPage.deleteFailed"));
    }
  } catch (error: any) {
    if (error.name !== 'cancel') {
      ElMessage.error(i18n.t("products.productPage.deleteFailed"));
      console.error('Failed to delete product:', error);
    }
  }
};

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  console.log(pageSize);
  searchParams.value.pageSize = pageSize;
  loadProductList();
};
const handlePaginationPageChange = (page: number) => {
  console.log(page);
  searchParams.value.page = page;
  loadProductList();
};

// 初始加载
onMounted(() => {
  loadProductList();
});

// 格式化设备类型
const formatDeviceType = (type: number) => {
  const typeMap = {
    0: i18n.t("products.productPage.directDevice"),
    1: i18n.t("products.productPage.gatewayDevice"),
    2: i18n.t("products.productPage.subDevice"),
  };
  return typeMap[type as keyof typeof typeMap] || i18n.t("products.productPage.unknownType");
};

// 格式化激活状态
const formatStatus = (status: number) => {
  return status === 1 ? i18n.t("products.productPage.active") : i18n.t("products.productPage.inactive");
};

// 控制弹框显示
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const currentProduct = ref<any>(null);

// 打开新增弹框
const openAddDialog = () => {
  addDialogVisible.value = true;
};

// 打开编辑弹框
const openEditDialog = (product: any) => {
  currentProduct.value = { ...product };
  editDialogVisible.value = true;
};

// 关闭弹框后的回调
const handleClose = () => {
  // 可以在这里添加一些清理逻辑
};

// 刷新列表
const refreshList = () => {
  loadProductList();
};

const router = useRouter();
const goToConfig = (productId: number) => {
  router.push({
    path: '/configs/productConfig',
    query: { productId }
  });
};

const goToDeptProductConfig = (productId: number) => {
  router.push({
    path: '/configs/deptProductConfig',
    query: { productId }
  });
};
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields= searchFields
          :initialValues="searchParams"
          :maxVisibleFields=3
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>

    <!--按钮区-->
    <div class="button-area">
      <el-button
      type="primary"
      icon="Plus"
      @click="openAddDialog"
    >
      {{ i18n.t("products.productPage.addProduct") }}
    </el-button>
    </div>

    <!-- 卡片列表 -->
    <div class="product-list-container">
      <div v-if="productList.length === 0" class="empty-state">
        <el-empty :description="i18n.t('products.productPage.noProductData')" />
      </div>
      <div v-else class="product-grid">
        <el-card
          v-for="product in productList"
          :key="product.id"
          class="product-card"
          :body-style="{ padding: '16px' }"
        >
          <div class="product-info">
            <div class="product-image">
              <img
                :src="product.image || '/images/default-product.png'"
                :alt="product.name"
                class="product-img"
              />
            </div>
            <div class="product-details">
              <h3 class="product-name">{{ product.name }}</h3>
              <div class="product-meta">
                <div class="meta-item">
                  <span class="meta-label">{{ i18n.t('products.productPage.metaLabel.productKey') }}</span>
                  <span class="meta-value">{{ product.productKey }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">{{ i18n.t('products.productPage.metaLabel.deviceType') }}</span>
                  <span class="meta-value">{{ formatDeviceType(product.type) }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">{{ i18n.t('products.productPage.metaLabel.status') }}</span>
                  <span
                    class="meta-value"
                    :class="product.openStatus === 1 ? 'status-active' : 'status-inactive'"
                  >
                    {{ formatStatus(product.openStatus) }}
                  </span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">{{ i18n.t('products.productPage.metaLabel.version') }}</span>
                  <span class="meta-value">{{ product.version }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">{{ i18n.t('products.productPage.metaLabel.createTime') }}</span>
                  <span class="meta-value">{{ product.createdAt }}</span>
                </div>
              </div>
              <div class="product-description">{{ product.description }}</div>
            </div>
          </div>
          <div class="product-actions">
            <el-dropdown>
              <el-button type="info" size="small" plain>
                {{ i18n.t('buttons.manage') }}
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openEditDialog(product)">{{ i18n.t('products.productPage.editProduct') }}</el-dropdown-item>
                  <el-dropdown-item @click="goToConfig(product.id)">{{ i18n.t('products.productPage.productConfig') }}</el-dropdown-item>
                  <el-dropdown-item @click="goToDeptProductConfig(product.id)">{{ i18n.t('products.productPage.deptProductConfig') }}</el-dropdown-item>
                  <el-dropdown-item @click="handleDelete(product.id)"   style="margin-top: 10px; color:red">{{ i18n.t('products.productPage.deleteProduct') }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="pageSizeOps"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handlePaginationSizeChange"
          @current-change="handlePaginationPageChange"
        />
      </div>
    </div>

    <!-- 新增弹框 -->
    <AddProduct
      v-model:visible="addDialogVisible"
      @close="handleClose"
      @success="refreshList"
    />

    <!-- 编辑弹框 -->
    <EditProduct
      v-model:visible="editDialogVisible"
      :product="currentProduct"
      @close="handleClose"
      @success="refreshList"
    />
  </el-card>
</template>

<style scoped lang="scss">
.product-list-container {
  padding: 20px 0;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.product-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.product-info {
  display: flex;
  margin-bottom: 16px;
  flex: 1;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
  flex-shrink: 0;
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-details {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px;
  margin-bottom: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.meta-label {
  color: #606266;
  margin-right: 4px;
}

.meta-value {
  color: #303133;
}

.status-active {
  color: #67c23a;
}

.status-inactive {
  color: #909399;
}

.product-description {
  font-size: 12px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>






